//logs.js
const util = require('../../utils/util.js')
const qcloud = require('../../vendor/wafer2-client-sdk/index')
Page({


  data: {
      imgw:1,
      skey:'',
      openid:'',
  logged: false,

     
      imgurl:[
        'http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg',
        'http://img06.tooopen.com/images/20160818/tooopen_sy_175866434296.jpg',
        'http://img06.tooopen.com/images/20160818/tooopen_sy_175833047715.jpg'
      ]
     
  },
  
// macwidth: function(){       
//        this.setData({
//        imgw:wx.getSystemInfoSync().windowWidth,
//        test:"do it"
//        })
//   },


  onLoad: function () {   
    var that=this;
     wx.login({
      success: function(res) {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: 'https://evekykeb.qcloud.la/login/getopid',
            data: {
              code: res.code
            },
            success:function (getit) {
                console.log(getit);
                if (getit.data.status == 200) {                    
                    getApp().globalData.openid=getit.data.openid; 
            
                    //获取临时患者列表
                    // that.patlist();                   
                } else {
                    wx.showToast({
                    title: '获取用户信息错误，无法进行业务咨询!',
                    icon: 'loading',
                    duration: 1500
                })
                    return;

                }

            },
            fail:function (err) {
                wx.showToast({
                    title: '无法连接网络，请检查网络信号!',
                    icon: 'loading',
                    duration: 1500
                })
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      },
      fail:function (err) {
        console.log(err)
      }
    });
 
  },



    // 登录信息
    login: function () {
        if (this.data.logged) return

        util.showBusy('正在登录')
        var that = this

        // 调用登录接口
        qcloud.login({
            success(result) {
                console.log('登录成功信息',result);
                if (result) {
                    util.showSuccess('登录成功');
                    that.setData({
                        userInfo: result,
                        logged: true
                    })
                } else {
                    // 如果不是首次登录，不会返回用户信息，请求用户信息接口获取
                    qcloud.request({
                        url: config.service.requestUrl,
                        login: true,
                        success(result) {
                            util.showSuccess('登录成功')
                            that.setData({
                                userInfo: result.data.data,
                                logged: true
                            })
                        },

                        fail(error) {
                            util.showModel('请求失败', error)
                            console.log('request fail', error)
                        }
                    })
                }
            },

            fail(error) {
                util.showModel('登录失败', error)
                console.log('登录失败', error)
            }
        })
    },




  

//检查用户是否有登录咨询模型，没有进入注册页面获取用户信息。
//如果有，进入选择列表进行咨询对象的选择。


 
// 以下数据无用，仅做测试
  patlist:function () {
    var list= [
      {"birthday":"2015-06-20","from_op":"oi2205Eu1a_R-XKOzbnZWFCdECrY","from_id":"56","pat_id":"5","pat_name":"张素敏","relation":"本人","sex":0},
      {"birthday":"2011-03-24","from_op":"oi2205Eu1a_R-XKOzbnZWFCdECrY","from_id":"56","pat_id":"8","pat_name":"李国丰","relation":"朋友","sex":1},
      {"birthday":"2004-06-20","from_op":"oi2205Eu1a_R-XKOzbnZWFCdECrY","from_id":"56","pat_id":"11","pat_name":"刘小美","relation":"爱人","sex":0}
      ];
  wx.setStorage({
    key:"patlist",
    data:list,
    success:function (res) {
      console.log(res);
    }
  });
  },




  // 测 试登录内容

  freepage:function(){
      var id = getApp().globalData.openid;
      var that=this;
 //获取当前用户id
          wx.request({
            url:'https://evekykeb.qcloud.la/login/ceck_openid',
            data:{
              openid:id
            },
            success:function (res) {
              if (res.status=200) {
                var tmpdata=res.data;
  // 检查返回用户数组数量，如果是1有记录登录过，0未登录过，进入注册页面
                if (tmpdata.data.length == 0) {
                 console.log('查询当前用户记录',tmpdata)

                  wx.navigateTo({
                    url: '../freereg/free1/free1'
                   })

                } else {
                getApp().globalData.userid = tmpdata.data[0].user_id;
                var tmpuserid = 'getApp().globalData.userid';
                getApp().globalData.logged = true;
                that.setData({
                  [tmpuserid]:tmpdata.data[0].user_id

                });
                console.log(getApp().globalData.openid,getApp().globalData.logged,getApp().globalData.userid)           
 // 获取患者列表
              wx.request({
                //login:true,
                url:'https://evekykeb.qcloud.la/weapp/SoboDb/getpatinfo',
                method:'get',
                header: {'content-type': 'application/json'},      
                data:{
                  oppenid:id

                },
                success:function (res) {
                  // 判断返回记录条数
                  console.log(res);
                  var length=res.data.length;
                  // 如果条数为1，进入患者页，否则进入注册页
                   console.log('记录数',length);
                   if (length == 1) {
                    // console.log(res.data);
                     wx.navigateTo({
                     url:'../freereg/free2/free2?oppenid='+id +'&userid='+res.data[0].user_id,
                     success:function (reg) {
                       //console.log(res);
                     },
                     fail:function (err) {
                      // console.log(err);
                     }
             })
                  } else {
                    //没有该用户记录，将用户信息写入      
                    
                    wx.navigateTo({
                    url: '../freereg/free1/free1'
                  })


                   }
                 },

                fail:function (error) {
                  console.log(error);
                  util.showModel('请求失败', error);

                }


              }) 


                } 
               
              } else {
                util.showModel('错误',res.data);

              }
            }
          })



  },


// 登录公共接口
   bindGetUserInfo: function (e) {
        if (this.data.logged) return;

        util.showBusy('正在登录');

        var that = this;
        var userInfo = e.detail.userInfo;
        console.log(userInfo);

        // 查看是否授权
        wx.getSetting({
            success: function (res) {
                if (res.authSetting['scope.userInfo']) {

                    // 检查登录是否过期
                    wx.checkSession({
                        success: function () {
                            // 登录态未过期
                            util.showSuccess('登录成功');
                            that.setData({
                                userInfo: userInfo,
                                logged: true
                            })
                        },

                        fail: function () {
                            qcloud.clearSession();
                            // 登录态已过期，需重新登录
                            var options = {
                                encryptedData: e.detail.encryptedData,
                                iv: e.detail.iv,
                                userInfo: userInfo
                            }
                            that.doLogin(options);
                        },
                    });
                } else {
                    util.showModel('用户未授权', e.detail.errMsg);
                }
            }
        });
    },

    doLogin: function (options) {
        var that = this;

        wx.login({
            success: function (loginResult) {
                var loginParams = {
                    code: loginResult.code,
                    encryptedData: options.encryptedData,
                    iv: options.iv,
                }
                qcloud.requestLogin({
                    loginParams, success() {
                        util.showSuccess('登录成功');

                        that.setData({
                            userInfo: options.userInfo,
                            logged: true
                        })
                    },
                    fail(error) {
                        util.showModel('登录失败', error)
                        console.log('登录失败', error)
                    }
                });
            },
            fail: function (loginError) {
                util.showModel('登录失败', loginError)
                console.log('登录失败', loginError)
            },
        });
    },

    // 切换是否带有登录态
    switchRequestMode: function (e) {
        this.setData({
            takeSession: e.detail.value
        })
        this.doRequest()
    },

    doRequest: function () {
        util.showBusy('请求中...')
        var that = this
        var options = {
            url: config.service.requestUrl,
            login: true,
            success(result) {
                util.showSuccess('请求成功完成')
                console.log('request success', result)
                that.setData({
                    requestResult: JSON.stringify(result.data)
                })
            },
            fail(error) {
                util.showModel('请求失败', error);
                console.log('request fail', error);
            }
        }
        if (this.data.takeSession) {  // 使用 qcloud.request 带登录态登录
            qcloud.request(options)
        } else {    // 使用 wx.request 则不带登录态
            wx.request(options)
        }
    },




})
